<template>
  <view class="publish-container">
    <scroll-view class="form-scroll" scroll-y>
      <form @submit="handleSubmit">
        <!-- 基本信息 -->
        <view class="form-section">
          <view class="section-title">基本信息</view>
          
          <view class="form-item">
            <text class="label required">信息类型</text>
            <view class="picker-wrapper">
              <picker
                :value="selectedTypeIndex"
                :range="listingTypes"
                @change="onTypeChange"
                class="form-picker"
              >
                <view class="picker-content">
                  <text class="picker-text">{{ listingTypes[selectedTypeIndex] || '请选择' }}</text>
                  <text class="picker-arrow">></text>
                </view>
              </picker>
            </view>
          </view>

          <view class="form-item">
            <text class="label required">公司名称</text>
            <input 
              v-model="formData.company_name"
              placeholder="请输入公司/个体户名称"
              class="form-input"
              maxlength="100"
            />
          </view>

          <view class="form-item">
            <text class="label">注册省份</text>
            <view class="picker-wrapper">
              <picker
                :value="selectedProvinceIndex"
                :range="provinces"
                @change="onProvinceChange"
                class="form-picker"
              >
                <view class="picker-content">
                  <text class="picker-text">{{ provinces[selectedProvinceIndex] || '请选择省份' }}</text>
                  <text class="picker-arrow">></text>
                </view>
              </picker>
            </view>
          </view>

          <view class="form-item">
            <text class="label">注册城市</text>
            <view class="picker-wrapper">
              <picker
                :value="selectedCityIndex"
                :range="cities"
                @change="onCityChange"
                class="form-picker"
              >
                <view class="picker-content">
                  <text class="picker-text">{{ cities[selectedCityIndex] || '请选择城市' }}</text>
                  <text class="picker-arrow">></text>
                </view>
              </picker>
            </view>
          </view>

          <view class="form-item">
            <text class="label">成立日期</text>
            <view class="picker-wrapper">
              <picker
                mode="date"
                :value="formData.establishment_date"
                @change="onDateChange"
                class="form-picker"
              >
                <view class="picker-content">
                  <text class="picker-text">{{ formatDisplayDate(formData.establishment_date) || '请选择日期' }}</text>
                  <text class="picker-arrow">></text>
                </view>
              </picker>
            </view>
          </view>
        </view>

        <!-- 价格信息 -->
        <view class="form-section">
          <view class="section-title">价格信息</view>
          
          <view class="form-item">
            <text class="label">价格设置</text>
            <radio-group @change="onPriceTypeChange">
              <view class="price-options">
                <label class="radio-item">
                  <radio 
                    value="negotiable"
                    :checked="formData.is_negotiable" 
                    color="#22c55e"
                  />
                  <text>面议</text>
                </label>
                <label class="radio-item">
                  <radio 
                    value="fixed"
                    :checked="!formData.is_negotiable" 
                    color="#22c55e"
                  />
                  <text>固定价格</text>
                </label>
              </view>
            </radio-group>
          </view>

          <view v-if="!formData.is_negotiable" class="form-item">
            <text class="label">售价（元）</text>
            <input 
              v-model="formData.price"
              placeholder="请输入售价"
              type="number"
              class="form-input"
            />
          </view>
        </view>

        <!-- 公司详情 -->
        <view class="form-section">
          <view class="section-title">公司详情</view>
          
          <view class="form-item">
            <text class="label">注册资本</text>
            <view class="picker-wrapper">
              <picker
                :value="selectedCapitalIndex"
                :range="capitalRanges"
                @change="onCapitalChange"
                class="form-picker"
              >
                <view class="picker-content">
                  <text class="picker-text">{{ capitalRanges[selectedCapitalIndex] || '请选择' }}</text>
                  <text class="picker-arrow">></text>
                </view>
              </picker>
            </view>
          </view>

          <view class="form-item">
            <text class="label">实缴状态</text>
            <view class="picker-wrapper">
              <picker
                :value="selectedPaidIndex"
                :range="paidStatuses"
                @change="onPaidChange"
                class="form-picker"
              >
                <view class="picker-content">
                  <text class="picker-text">{{ paidStatuses[selectedPaidIndex] || '请选择' }}</text>
                  <text class="picker-arrow">></text>
                </view>
              </picker>
            </view>
          </view>

          <view class="form-item">
            <text class="label">{{ getCompanyTypeLabel() }}</text>
            <view class="picker-wrapper">
              <picker
                :value="selectedCompanyTypeIndex"
                :range="companyTypes"
                @change="onCompanyTypeChange"
                class="form-picker"
              >
                <view class="picker-content">
                  <text class="picker-text">{{ companyTypes[selectedCompanyTypeIndex] || '请选择' }}</text>
                  <text class="picker-arrow">></text>
                </view>
              </picker>
            </view>
          </view>

          <view class="form-item">
            <text class="label">税务情况</text>
            <view class="picker-wrapper">
              <picker
                :value="selectedTaxIndex"
                :range="taxStatuses"
                @change="onTaxChange"
                class="form-picker"
              >
                <view class="picker-content">
                  <text class="picker-text">{{ taxStatuses[selectedTaxIndex] || '请选择' }}</text>
                  <text class="picker-arrow">></text>
                </view>
              </picker>
            </view>
          </view>

          <view class="form-item">
            <text class="label">纳税等级</text>
            <view class="picker-wrapper">
              <picker
                :value="selectedTaxGradeIndex"
                :range="taxGrades"
                @change="onTaxGradeChange"
                class="form-picker"
              >
                <view class="picker-content">
                  <text class="picker-text">{{ taxGrades[selectedTaxGradeIndex] || '请选择' }}</text>
                  <text class="picker-arrow">></text>
                </view>
              </picker>
            </view>
          </view>

          <view class="form-item">
            <text class="label">银行账户</text>
            <view class="picker-wrapper">
              <picker
                :value="selectedBankIndex"
                :range="bankStatuses"
                @change="onBankChange"
                class="form-picker"
              >
                <view class="picker-content">
                  <text class="picker-text">{{ bankStatuses[selectedBankIndex] || '请选择' }}</text>
                  <text class="picker-arrow">></text>
                </view>
              </picker>
            </view>
          </view>

          <view class="form-item">
            <text class="label">银行流水</text>
            <input
              v-model="formData.bank_flow"
              placeholder="请输入银行流水情况"
              class="form-input"
              maxlength="255"
            />
          </view>
        </view>

        <!-- 资产情况 -->
        <view class="form-section">
          <view class="section-title">资产情况</view>
          
          <view class="checkbox-grid">
            <view class="checkbox-item" @click="toggleAsset('has_trademark')">
              <checkbox
                :checked="formData.has_trademark"
                color="#22c55e"
              />
              <text>商标</text>
            </view>
            <view class="checkbox-item" @click="toggleAsset('has_patent')">
              <checkbox
                :checked="formData.has_patent"
                color="#22c55e"
              />
              <text>专利</text>
            </view>
            <view class="checkbox-item" @click="toggleAsset('has_software_copyright')">
              <checkbox
                :checked="formData.has_software_copyright"
                color="#22c55e"
              />
              <text>软著</text>
            </view>
            <view class="checkbox-item" @click="toggleAsset('has_license_plate')">
              <checkbox
                :checked="formData.has_license_plate"
                color="#22c55e"
              />
              <text>车牌指标</text>
            </view>
            <view class="checkbox-item" @click="toggleAsset('has_social_security')">
              <checkbox
                :checked="formData.has_social_security"
                color="#22c55e"
              />
              <text>社保记录</text>
            </view>
            <view class="checkbox-item" @click="toggleAsset('has_bidding_history')">
              <checkbox
                :checked="formData.has_bidding_history"
                color="#22c55e"
              />
              <text>招投标业绩</text>
            </view>
          </view>
        </view>

        <!-- 详细描述 -->
        <view class="form-section">
          <view class="section-title">详细描述</view>
          
          <view class="form-item">
            <textarea 
              v-model="formData.description"
              placeholder="请详细描述公司情况、转让原因等（选填）"
              class="form-textarea"
              maxlength="500"
            />
            <text class="char-count">{{ formData.description?.length || 0 }}/500</text>
          </view>
        </view>
      </form>
    </scroll-view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <button 
        class="submit-btn" 
        :class="{ disabled: isSubmitting }"
        @click="handleSubmit"
        :disabled="isSubmitting"
      >
        {{ isSubmitting ? '发布中...' : '发布信息' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { listingAPI, userAPI, utils } from '@/utils/api.js'
import { getProvinces, getCitiesByProvince } from '@/utils/areaData.js'
import CreditChecker from '@/utils/creditChecker.js'

// 响应式数据
const isSubmitting = ref(false)

// 表单数据
const formData = reactive({
  listing_type: '',
  company_name: '',
  registration_province: '',
  registration_city: '',
  establishment_date: '',
  price: '',
  is_negotiable: true,
  registered_capital_range: '',
  paid_in_status: '',
  company_type: '',
  tax_status: '',
  tax_grade: '',
  bank_account_status: '',
  bank_flow: '',
  has_trademark: false,
  has_patent: false,
  has_software_copyright: false,
  has_license_plate: false,
  has_social_security: false,
  has_bidding_history: false,
  description: ''
})

// 选择器数据
const listingTypes = ['公司', '个体户', '代账户']
const selectedTypeIndex = ref(-1)

// 使用完整的省市数据
const provinces = getProvinces()
const selectedProvinceIndex = ref(-1)

const cities = ref(['请先选择省份'])
const selectedCityIndex = ref(-1)

const capitalRanges = ['10万以下', '10-50万', '50-100万', '100-500万', '500-1000万', '1000万以上']
const selectedCapitalIndex = ref(-1)

const paidStatuses = ['已实缴', '未实缴', '不确定']
const selectedPaidIndex = ref(-1)

// 原始公司类型选项
const originalCompanyTypes = ['普通公司', '国家局公司', '上市公司', '不确定']
// 个体户类型选项
const individualTypes = ['个人经营', '家庭经营']
// 当前显示的类型选项（动态变化）
const companyTypes = ref(['普通公司', '国家局公司', '上市公司', '不确定'])
const selectedCompanyTypeIndex = ref(-1)

const taxStatuses = ['未登记', '小规模', '一般纳税人', '未开业', '不确定']
const selectedTaxIndex = ref(-1)

const taxGrades = ['A', 'B', 'M', 'C', 'D', '未开通']
const selectedTaxGradeIndex = ref(-1)

const bankStatuses = ['已开户', '未开户', '不确定']
const selectedBankIndex = ref(-1)

// 方法定义
const onTypeChange = (e) => {
  selectedTypeIndex.value = e.detail.value
  formData.listing_type = listingTypes[e.detail.value]
  
  // 根据信息类型动态调整公司类型选项
  updateCompanyTypeOptions(formData.listing_type)
}

const onProvinceChange = (e) => {
  selectedProvinceIndex.value = e.detail.value
  const selectedProvince = provinces[e.detail.value]
  formData.registration_province = selectedProvince

  // 重置城市选择
  selectedCityIndex.value = -1
  formData.registration_city = ''

  // 更新城市列表
  if (selectedProvince) {
    cities.value = getCitiesByProvince(selectedProvince)
  } else {
    cities.value = ['请先选择省份']
  }
}

const onCityChange = (e) => {
  selectedCityIndex.value = e.detail.value
  formData.registration_city = cities.value[e.detail.value]
}

const onDateChange = (e) => {
  formData.establishment_date = e.detail.value
}

const onCapitalChange = (e) => {
  selectedCapitalIndex.value = e.detail.value
  formData.registered_capital_range = capitalRanges[e.detail.value]
}

const onPaidChange = (e) => {
  selectedPaidIndex.value = e.detail.value
  formData.paid_in_status = paidStatuses[e.detail.value]
}

const onCompanyTypeChange = (e) => {
  selectedCompanyTypeIndex.value = e.detail.value
  formData.company_type = getActualCompanyTypeValue(companyTypes.value[e.detail.value], formData.listing_type)
}

const onTaxChange = (e) => {
  selectedTaxIndex.value = e.detail.value
  formData.tax_status = taxStatuses[e.detail.value]
}

const onTaxGradeChange = (e) => {
  selectedTaxGradeIndex.value = e.detail.value
  formData.tax_grade = taxGrades[e.detail.value]
}

const onBankChange = (e) => {
  selectedBankIndex.value = e.detail.value
  formData.bank_account_status = bankStatuses[e.detail.value]
}



const onPriceTypeChange = (e) => {
  const value = e.detail.value
  formData.is_negotiable = value === 'negotiable'
  if (formData.is_negotiable) {
    formData.price = ''
  }
}

const toggleAsset = (field) => {
  formData[field] = !formData[field]
}

// 根据信息类型更新公司类型选项
const updateCompanyTypeOptions = (listingType) => {
  if (listingType === '个体户') {
    companyTypes.value = [...individualTypes]
  } else {
    companyTypes.value = [...originalCompanyTypes]
  }
  
  // 重置公司类型选择
  selectedCompanyTypeIndex.value = -1
  formData.company_type = ''
}

// 获取公司类型标签
const getCompanyTypeLabel = () => {
  return formData.listing_type === '个体户' ? '个体户类型' : '公司类型'
}

// 获取实际的公司类型值（映射个体户类型到现有枚举）
const getActualCompanyTypeValue = (displayValue, listingType) => {
  if (listingType === '个体户') {
    // 将个体户类型映射到现有的公司类型枚举值
    if (displayValue === '个人经营') {
      return '普通公司'  // 复用普通公司枚举
    } else if (displayValue === '家庭经营') {
      return '国家局公司'  // 复用国家局公司枚举
    }
  }
  return displayValue
}

// 格式化日期显示
const formatDisplayDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}年${month}月${day}日`
}

// 重置表单数据
const resetForm = () => {
  // 重置表单数据
  Object.assign(formData, {
    listing_type: '',
    company_name: '',
    registration_province: '',
    registration_city: '',
    establishment_date: '',
    price: '',
    is_negotiable: true,
    registered_capital_range: '',
    paid_in_status: '',
    company_type: '',
    tax_status: '',
    tax_grade: '',
    bank_account_status: '',
    shareholder_background: '',
    has_trademark: false,
    has_patent: false,
    has_software_copyright: false,
    has_license_plate: false,
    has_social_security: false,
    has_bidding_history: false,
    description: ''
  })

  // 重置选择器索引
  selectedTypeIndex.value = -1
  selectedProvinceIndex.value = -1
  selectedCityIndex.value = -1
  selectedCapitalIndex.value = -1
  selectedPaidIndex.value = -1
  selectedCompanyTypeIndex.value = -1
  selectedTaxIndex.value = -1
  selectedTaxGradeIndex.value = -1
  selectedBankIndex.value = -1

  // 重置城市列表
  cities.value = ['请先选择省份']
}

// 检查用户激活状态
const checkUserActivation = async () => {
  try {
    const response = await userAPI.getCurrentUser()
    if (response.success) {
      return {
        isActivated: response.data.status === 'active',
        userInfo: response.data
      }
    }
    return { isActivated: false }
  } catch (error) {
    console.error('检查激活状态失败:', error)
    return { isActivated: false }
  }
}

// 显示激活弹窗
const showActivationModal = () => {
  uni.showModal({
    title: '系统提示',
    content: '您的账号未激活，暂不能使用此功能。',
    confirmText: '去激活',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        // 跳转到激活页面（套餐购买或邀请页面）
        uni.navigateTo({
          url: '/pages/packages/packages'
        })
      }
    }
  })
}

const validateForm = () => {
  const errors = []
  
  if (!formData.listing_type) {
    errors.push('请选择信息类型')
  }
  
  if (!formData.company_name?.trim()) {
    errors.push('请输入公司名称')
  }
  
  if (!formData.is_negotiable && (!formData.price || formData.price <= 0)) {
    errors.push('请输入有效的售价')
  }
  
  return errors
}

const handleSubmit = async () => {
  if (isSubmitting.value) return

  // 检查用户激活状态
  const userInfo = await checkUserActivation()
  if (!userInfo.isActivated) {
    showActivationModal()
    return
  }

  // 检查发布额度
  const hasCredit = await CreditChecker.checkPublishingCredit({
    fromPage: '/pages/listings/publish'
  })
  if (!hasCredit) {
    return
  }

  // 表单验证
  const errors = validateForm()
  if (errors.length > 0) {
    uni.showToast({
      title: errors[0],
      icon: 'none'
    })
    return
  }
  
  try {
    isSubmitting.value = true
    
    // 构建提交数据
    const submitData = { ...formData }
    
    // 处理价格
    if (submitData.is_negotiable) {
      submitData.price = null
    } else {
      submitData.price = parseFloat(submitData.price)
    }
    
    const response = await listingAPI.createListing(submitData)
    
    if (response.success) {
      // 减少本地发布额度
      CreditChecker.reduceLocalCredit('publishing', 1)

      // 显示服务器返回的消息，包含审核相关信息
      uni.showModal({
        title: '发布成功',
        content: response.message || '发布成功',
        showCancel: false,
        confirmText: '确定'
      })

      // 重置表单数据
      resetForm()

      setTimeout(() => {
        // 检查来源页面，如果是从聊天页面进入的，则跳转回聊天页面
        const pages = getCurrentPages()
        const prevPage = pages[pages.length - 2]

        if (prevPage && prevPage.route === 'pages/chat/chat') {
          // 从聊天页面进入，跳转回聊天页面
          uni.navigateTo({ url: '/pages/chat/chat' })
        } else {
          // 从其他页面进入，使用默认的返回行为
          uni.navigateBack()
        }
      }, 1500)
    } else {
      utils.handleError(new Error(response.message), '发布失败')
    }
    
  } catch (error) {
    utils.handleError(error, '发布失败')
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.publish-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.form-scroll {
  flex: 1;
  padding: 20rpx;
}

.form-section {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  padding-bottom: 15rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.label.required::after {
  content: '*';
  color: #ef4444;
  margin-left: 5rpx;
}

.form-input {
  width: 100%;
  height: 60rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: white;
  box-sizing: border-box;
  line-height: 60rpx;
}

.picker-wrapper {
  width: 100%;
  position: relative;
  /* 增加额外的点击区域 */
  padding: 8rpx 0;
  margin: -8rpx 0;
}

.form-picker {
  width: 100%;
  height: 60rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  background: white;
  /* 确保picker本身可以接收点击事件 */
  position: relative;
  overflow: hidden;
}

.picker-content {
  height: 100%;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 28rpx;
  color: #333;
  /* 确保内容区域完全填充picker */
  width: 100%;
  box-sizing: border-box;
  /* 防止内容区域阻止点击事件 */
  pointer-events: none;
  /* 确保文字垂直居中 */
  line-height: 60rpx;
}

/* 为picker添加更明显的点击反馈 */
.form-picker:active {
  background-color: #f0f0f0;
  transform: scale(0.98);
  transition: all 0.1s ease;
}

/* 优化picker文本样式 */
.picker-text {
  flex: 1;
  pointer-events: none;
  line-height: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
}

/* 确保箭头不会阻止点击 */
.picker-arrow {
  color: #999;
  pointer-events: none;
  font-size: 24rpx;
  line-height: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
}

.picker-arrow {
  color: #999;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: white;
}

.char-count {
  display: block;
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.price-options {
  display: flex;
  gap: 40rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  font-size: 28rpx;
}

.checkbox-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  font-size: 28rpx;
  padding: 20rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  background: #f9f9f9;
  cursor: pointer;
  transition: background-color 0.2s;
}

.checkbox-item:active {
  background: #e5e5e5;
}

.submit-section {
  padding: 20rpx;
  background: white;
  border-top: 1rpx solid #eee;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  background: #22c55e;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.submit-btn.disabled {
  background: #ccc;
}
</style>
